const express = require("express");
const router = express.Router();
const db = require("../db");
const base = require("../base");
const moment = require("moment");

// ---------------- 分页获取文章列表 ----------------
router.post("/list", async (req, res) => {
  // 设置变量，接收请求参数
  let { pageNum, pageSize, type, state } = req.body;
  // 根据type 和 state制作SQL语句的条件
  let w = "";
  if (type) {
    w += ` where type=${type} `;
  }
  // if (state) {
  //   w += ` and state='${state}' `;
  // }
  // 分页查询数据的SQL（该SQL用到了连表查询，并且使用了很多变量组合）
  let sql1 = `select id,createdById,createdByTime,title,content,type,state from article ${w} order by id desc limit ${
    (pageNum - 1) * pageSize
  }, ${pageSize}`;
  // 查询总记录数的SQL，查询条件和前面查询数据的条件 必须要一致
  let sql2 = `select count(*) total from article ${w}`;
  // 分别执行两条SQL（因为db查询数据库是异步方法，必须嵌套查询）
  const result1 = await db(sql1);
  const result2 = await db(sql2);
  const result3 = await base(result1);
  res.send({
    status: 0,
    message: "获取文章列表数据成功",
    data: result3,
    total: result2[0].total,
  });
});

//新增文章
router.post("/add", async (req, res) => {
  let date = moment().format("YYYY-MM-DD HH:mm:ss");
  const { createdById, title, content, type, state } = req.body;
  let sql = `insert into article set createdById=${createdById},createdByTime='${date}',title='${title}',content='${content}',type='${type}',state='${state}'`;
  await db(sql);
  res.send({ status: 0, message: "新增成功" });
});

//获取文章详情
router.get("/message", async (req, res) => {
  const { id } = req.query;
  const result1 = await db(`select * from article where id=${id}`);
  const result2 = await base(result1);
  res.send({ status: 0, message: "获取文章数据成功", data: result2[0] });
});

//删除文章
router.delete("/message", async (req, res) => {
  const { id } = req.query;
  await db(`delete from article where id=${id}`);
  res.send({ status: 0, message: "删除文章数据成功" });
});

module.exports = router;
